<template>
  <div class="table-box">
    <Table
        ref="table"
        :searchColumns="searchColumns"
        description_keywords="userManage"
        @getTableList="getTableList"
    >
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="showUserFrom('create')">新增用户</el-button>
      </template>
      <template #table>
        <!-- 表格主体 -->
        <el-table :data="tableList"
                  border
                  style="width: 100%">
          <el-table-column prop="username" fixed="left" align="center" label="账号" width="200"/>
          <el-table-column align="center" label="头像👤" width="150">
            <template #default="scope">
              <div v-if="scope.row.avatar" class="table-pic" >
                <img :src="baseURL + scope.row.avatar" alt="暂无头像">
              </div>
              <span v-else>暂无头像</span>
            </template>
          </el-table-column>
          <el-table-column prop="nickname" align="center" label="昵称" width="200"/>
          <el-table-column prop="mobile" align="center" label="手机号📱" width="150"/>
          <el-table-column prop="email" align="center" label="邮箱📮" width="200"/>
          <el-table-column prop="gender_display" align="center" label="性别" width="150"/>
          <el-table-column prop="is_active" align="center" label="是否启用" width="150">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.is_active"
                  @change=""
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
              />
            </template>
          </el-table-column>
          <el-table-column prop="is_superuser" align="center" label="是否超级用户" width="200">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.is_superuser"
                  disabled
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
              />
            </template>
          </el-table-column>
          <el-table-column prop="last_login" align="center" label="最后登陆时间" width="200"/>
          <el-table-column prop="create_time" align="center" label="创建时间" width="200"/>
          <!--          <el-table-column prop="update_time" align="center" label="修改时间" width="200"/>-->
          <el-table-column align="center" fixed="right" label="操作" min-width="150px">
            <template #default="scope">
              <el-button
                  @click=""
                  size="small">编辑
              </el-button>
              <el-button
                  @click=""
                  size="small">启用
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </Table>

    <el-dialog v-model="userFormDialogVisible" :title="userFormDialogTitle" width="800" draggable>

      <el-form ref="userFormRef" :model="userFormData" :rules="userRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号:" prop="username">
              <el-input style="width: 100%;"
                        maxlength="40"
                        v-model.trim="userFormData.username"
                        placeholder=请输入账号>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称:" prop="nickname">
              <el-input style="width: 100%;"
                        maxlength="20"
                        v-model.trim="userFormData.nickname"
                        placeholder=请输入昵称>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像:">
              <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="uploadSectionFile"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove"
              >
                <img v-if="userFormData.avatar" :src="baseURL + userFormData.avatar" alt="" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别:">
              <el-select style="width: 100%;"
                         v-model="userFormData.gender"
                         placeholder="请选择性别">
                <el-option label="未知 " value="0"/>
                <el-option label="男" value="1"/>
                <el-option label="女" value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号:" prop="mobile">
              <el-input style="width: 100%;"
                        v-model="userFormData.mobile"
                        maxlength="11"
                        placeholder=请输入手机号>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱:" prop="email">
              <el-input style="width: 100%;"
                        v-model="userFormData.email"
                        placeholder=请输入邮箱>
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="超级用户:">
              <el-switch v-model="userFormData.is_superuser">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用:">
              <el-switch v-model="userFormData.is_active">
              </el-switch>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="">取消</el-button>
          <el-button type="primary" @click="commitUserFrom(userFormRef)">
            确定
          </el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup name="userManage">

// 需要搜索的配置项
import {computed, onMounted, reactive, ref} from "vue";
import {getUserList, postAvatarFile, postUser} from "@/api/modules/user.js";
import {CirclePlus, Delete, Plus} from "@element-plus/icons-vue";
import Table from "@/components/Table/index.vue";
import {ElMessage} from "element-plus";
import {postProjectApi} from "@/api/modules/project/projectManage.js";

const searchColumns = ref([
  {label: "账号", field: "username", searchType: "input"},
  {label: "昵称", field: "nickname", searchType: "input"},
  {label: "手机号", field: "mobile", searchType: "input"},
  {label: "邮箱", field: "email", searchType: "input"},
])

const tableList = ref([])

onMounted(() => {
  getTableList()
})

const table = ref(null)
const searchArgsDict = ref({a: 2})
const getTableList = async (searchArgs) => {
  const {data} = await getUserList(searchArgs)
  searchArgsDict.value = searchArgs
  tableList.value = data.data
  table.value.pageable.pageNum = data.page
  table.value.pageable.pageSize = data.pagesize
  table.value.pageable.total = data.total
}


// const deleteLoginLog = async (scope) => {
//   await deleteLoginInfoListApi({"ids": [scope.row.id]}).then(() => {
//     ElMessage.success("成功");
//     getTableList(searchArgsDict.value);
//   })
// }
//
// const deleteSelectionLoginLog = async () => {
//   await deleteLoginInfoListApi({"ids": selectionsIds.value}).then(() => {
//     ElMessage.success("成功");
//     getTableList(searchArgsDict.value);
//   })
// }

const userFormDialogVisible = ref(false)
const userFormDialogTitle = ref("")
const userFormData = ref({})

const showUserFrom = (formType) => {
  userFormDialogVisible.value = true
  if (formType === "create") {
    userFormDialogTitle.value = "新增用户"
  }
  if (formType === "update") {
    userFormDialogTitle.value = "编辑用户"
  }
}

const baseURL = import.meta.env.VITE_API_URL

const uploadSectionFile = (params) => {
  const file = params.file
  // const fileType = file.type
  // const isImage = fileType.indexOf("image") !== -1
  // const isLt4M = file.size / 1024 / 1024 < 4;
  // 这里常规检验，看项目需求而定
  // if (!isImage) {
  //   ElMessage.error("只能上传图片格式png、jpg、gif!");
  //   return;
  // }
  // 根据后台需求数据格式
  const form = new FormData();
  // 文件对象
  form.append("file", file);
  // form.append("Content-Type", 'multipart/form-data');
  // 上传头像的请求方法
  postAvatarFile(form).then(res => {
    userFormData.value.avatar = res.data
  })
}


const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('头像图片不能大于 4MB!')
    return false
  }
  if (["image/png", "image/jpg", "image/jpeg", "image/gif"].indexOf(rawFile.type) === -1) {
    ElMessage.error('请上传png,jpg,jpeg,gif格式的图片')
    return false
  }
  return true
}

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}


const userFormRef = ref(null);
const userRules = reactive({
  username: [
    {required: true, message: "请输入账号", trigger: "blur"}
  ],
  nickname: [{required: true, message: "请输入昵称", trigger: "blur"}],
  mobile: [
    {required: true, message: "请输入手机号", trigger: "blur"},
    {type: 'string', len: 11, message: "请输入11位手机号", trigger: "blur"},
    {required: true, pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  email: [
    {required: true, type: 'email', message: "请输入邮箱", trigger: ['blur', 'change']}
  ],
});


const loading = ref(false);
// 新增用户
const commitUserFrom = (formEl) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      postUser(userFormData.value)
    } finally {
      loading.value = false;
    }
  })
}


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
  border-radius: 50%;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}

</style>
